package cn.demo.text.editor.strategy.menu.action;

import cn.demo.text.editor.constant.RunParam;
import cn.demo.text.editor.constant.Str;
import cn.demo.text.editor.strategy.format.process.Format;
import cn.demo.text.editor.strategy.format.process.FormatFactory;

import javax.swing.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class SaveAction implements Action {

    @Override
    public void operate(JTextArea jta) throws Exception {
        String filePath = RunParam.context.get(Str.FILE_PATH);

        if (filePath == null || "".equals(filePath)) {
            SaveAsAction saveAsAction = new SaveAsAction();
            saveAsAction.operate(jta);
            return;
        }

        File file = new File(filePath);
        BufferedWriter bw = null;

        try {
            FileWriter fw = new FileWriter(filePath);
            bw = new BufferedWriter(fw);
            String jtaText = jta.getText();

            Format format = FormatFactory.getFormat(file.getName().substring(file.getName().lastIndexOf(".")));
            String[] split = jtaText.split("\\r?\\n");
            StringBuilder jtaTextSb = new StringBuilder();
            for (String line : split) {
                String analysis = format.analysis(Str.SAVE_AS, line);
                jtaTextSb.append(analysis).append(Str.Slash_R_Slash_N);
            }
            jtaText = jtaTextSb.toString();

            bw.write(jtaText);
        } finally {
            if (bw != null) bw.close();
        }
    }

}
